const fetchList = require('./fetch.js')
const {insert, insertHistory} = require('./db.js')
const detail = require('./detail.js')
const puppeteer = require('puppeteer')

async function run() {
    const browser = await puppeteer.launch()
    let page = await browser.newPage()
    let bondList = await fetchList(page)
    page = await browser.newPage()
    for (let i = 0; i < bondList.length; i++) {
        let {bondcode, sname} = bondList[i]
        console.log(`fetch ${sname}(${bondcode})...`)
        let {convertible, history} = await detail(page, bondcode)
        console.log(`fetch done, begin to save convertible...`)
        await insert(convertible)
        console.log('save convertible done, begin to save history...')
        await insertHistory(convertible.bondcode, history)
        console.log('save history done.')
        await page.waitForTimeout(3000)
    }
    await browser.close()
}

run().catch(err => {
    console.log(err)
    process.exit(1)
})
